﻿// Apache-2.0 License
// Copyright (c) 2021-2022 朱飞龙
// 电话/微信：18706708563  QQ群：136192142

#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 版权所有 (c) 2023   保留所有权利。
 * 命名空间：Radius.NET.ThirdParty.API.Service.KingdeeIcloud.Qc
 * 唯一标识：8bd4b51f-840d-46a5-837b-0198099101a2
 * 文件名：QmInspectBillService
 * 当前用户域：DESKTOP-6O7KN8G
 * 
 * 创建者：Administrator
 * 电子邮箱：radiuszfl@163.com
 * 创建时间：2023/3/6 11:03:24
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>

using Admin.NET.Application.Util.Extension;
using Radius.NET.Interface.Kingdee.Entity;
using System.Globalization;


namespace Radius.NET.Interface.Kingdee.Service.Qc;

/// <summary>
/// 质检单服务
/// </summary>
[ApiDescriptionSettings(KingdeeConfigConst.GroupName, Order = 005)]
public abstract class QmInspectBillService : IDynamicApiController, ITransient
{
    private readonly KingdeeUtil _kingdeeUtil;
    private readonly SqlSugarRepository<IqcCheckReport> _iqcCheckReportRep;
    private readonly SqlSugarRepository<FqcReport> _fqcReportRep;

    protected QmInspectBillService(KingdeeUtil kingdeeUtil,
        SqlSugarRepository<IqcCheckReport> iqcCheckReportRep,
        SqlSugarRepository<FqcReport> fqcReportRep)
    {
        _kingdeeUtil = kingdeeUtil;
        _iqcCheckReportRep = iqcCheckReportRep;
        _fqcReportRep = fqcReportRep;
    }

    #region 同步检验到本地
    /// <summary>
    /// 同步检验到本地
    /// </summary>
    /// <param name="cid"></param>
    /// <param name="bdate"></param>
    /// <param name="fbillNo"></param>
    /// <returns></returns>
    [HttpPost("/kindeeIcloud/QmInspect/list/{cid:int}"), AllowAnonymous]
    public async Task<object> GetQmInspectList(int cid, string bdate, string fbillNo)
    {
        try
        {
            var kingdeeUtil = await _kingdeeUtil.GetClient("kindeeIcloud_qmInspect_getlist");
            if (string.IsNullOrEmpty(bdate))
                bdate = DateTime.Now.ToString(CultureInfo.InvariantCulture);

            List<IqcCheckReport> iqcCheckList = new();
            List<FqcReport> fqcList = new();

            string filterString = $"FSourceOrgId.FNumber = '{KingdeeConfigConst.ORGID}' and FDate >= '{bdate}' and FDocumentStatus='C' and FQCStatus='3' and FBillTypeID.Fnumber in('JYD001_SYS','JYD002_SYS')";
            if (!string.IsNullOrEmpty(fbillNo))
            {
                filterString += $" and FBillNo = '{fbillNo}'";
            }

            var list = kingdeeUtil.Query<QM_InspectBillDto>(KingdeeFormConst.QM_InspectBill, filterString);
            int eviCount = 0;
            foreach (var item in list)
            {
                string fBillType = item.FBillTypeIdFNumber;
                string iqcNo = item.FBillNo;
                string inventoryId = item.FMaterialFNumber;
                string fLot = item.FLotFNumber;
                if (!iqcCheckList.Exists(x =>
                x.Iqcno.Contains(iqcNo)
                && x.InventoryId == inventoryId && x.Project == fLot))
                {
                    if (eviCount == 0)
                    {
                        eviCount++;
                    }
                    else
                    {
                        iqcNo += "_" + eviCount;
                        eviCount++;
                    }
                }

                var iqcCheckRecord = iqcCheckList.Find(x => x.Iqcno.Contains(iqcNo) && x.InventoryId == inventoryId && x.Project == fLot);

                #region 来料检验
                switch (fBillType)
                {
                    //来料检验
                    case "JYD001_SYS":
                    {
                        if (!await _iqcCheckReportRep.IsAnyAsync(x => x.Iqcno == iqcNo))
                        {
                            if (iqcCheckRecord == null)
                            {
                                iqcCheckList.Add(new IqcCheckReport()
                                {
                                    Iqcno = iqcNo,
                                    Date = item.FDate,
                                    InventoryId = inventoryId,
                                    ToreceiveQty = item.FInspectQty.ParseToDecimal(),
                                    PickQty = item.FInspectQty.ParseToDecimal(),
                                    InDate = item.FDate,
                                    Verdict = item.FInspectResult.Equals("1") ? "合格" : "不合格",
                                    Good = item.FInspectResult.Equals("1") ? -1 : 0,
                                    ReceiveBit = item.FInspectResult.Equals("1") ? -1 : 0,
                                    Reject = item.FInspectResult.Equals("1") ? 0 : -1,
                                    Project = fLot,
                                    QCStandNO = item.FQCSchemeIdFNumber,
                                    IQCtype = "全检",
                                    CreateDate = DateTime.Now,
                                    EvidenceNumber = item.FSrcBillNo,
                                    OrderID = item.FOrderBillNo,
                                    Cid = cid,
                                    FG_InvDetail = new List<IqcCheckReportDetail>(){
                                        new IqcCheckReportDetail()
                                        {
                                            Noid=item.FItemDetail_FSeq,
                                            Iqcno = iqcNo,
                                            ItemNo = item.FInspectItemIdFNumber,
                                            FLogic="介于",
                                            Verdict = item.FInspectResult.Equals("1") ? "合格" : "不合格",
                                            CheckValueText = item.FQualityStdIdFName,
                                            CheckRecord = item.F_GDRJ_Text,
                                            Cid = cid,
                                        }
                                    }
                                });
                            }
                            else
                            {
                                iqcCheckRecord.FG_InvDetail.Add(new IqcCheckReportDetail()
                                {
                                    Noid = item.FItemDetail_FSeq,
                                    Iqcno = iqcCheckRecord.Iqcno,
                                    ItemNo = item.FInspectItemIdFNumber,
                                    FLogic = "介于",
                                    Verdict = item.FInspectResult.Equals("1") ? "合格" : "不合格",
                                    CheckValueText = item.FQualityStdIdFName,
                                    CheckRecord = item.F_GDRJ_Text,
                                    Cid = cid,
                                });
                            }
                        }

                        break;
                    }
                    //产品检验单
                    case "JYD002_SYS":
                    {
                        if (!await _fqcReportRep.IsAnyAsync(x => x.No == iqcNo))
                        {
                            var fqcListRecord = fqcList.Find(x => x.No == iqcNo && x.InventoryId == inventoryId);
                            if (fqcListRecord == null)
                            {
                                fqcList.Add(new FqcReport()
                                {
                                    No = iqcNo,
                                    Date = item.FDate,
                                    InventoryId = inventoryId,
                                    Qty = item.FInspectQty.ParseToDecimal(),
                                    ProjectQty = item.FInspectQty.ParseToDecimal(),
                                    INDate = item.FDate,
                                    Verdict = item.FInspectResult.Equals("1") ? "合格" : "不合格",
                                    Good = item.FInspectResult.Equals("1") ? -1 : 0,
                                    ReceiveBit = item.FInspectResult.Equals("1") ? -1 : 0,
                                    Reject = item.FInspectResult.Equals("1") ? 0 : -1,
                                    Po = item.FOrderBillNo.ParseToString() + "_" + item.FOrderEntrySeq.ParseToString(),
                                    QCStandNO = item.FQCSchemeIdFNumber,
                                    ReType = "全检",
                                    CreateDate = DateTime.Now,
                                    Type = 1,
                                    Cid = cid,
                                    EvidenceNumber = item.FSrcBillNo,
                                    FG_InvDetail = new List<FqcReportDetail>() {
                                        new FqcReportDetail()
                                        {
                                            Noid=item.FItemDetail_FSeq,
                                            No = iqcNo,
                                            ItemNo = item.FInspectItemIdFNumber,
                                            FLogic="介于",
                                            Verdict = item.FInspectResult.Equals("1") ? "合格" : "不合格",
                                            CheckValueText = item.FQualityStdIdFName,
                                            CheckRecord = item.F_GDRJ_Text,
                                            Cid = cid,
                                        }
                                    }
                                });
                            }
                            else
                            {
                                fqcList.Find(x => x.No == iqcNo && x.InventoryId == inventoryId)
                                    .FG_InvDetail
                                    .Add(new FqcReportDetail()
                                    {
                                        Noid = item.FItemDetail_FSeq,
                                        No = iqcNo,
                                        ItemNo = item.FInspectItemIdFNumber,
                                        FLogic = "介于",
                                        Verdict = item.FInspectResult.Equals("1") ? "合格" : "不合格",
                                        CheckValueText = item.FQualityStdIdFName,
                                        CheckRecord = item.F_GDRJ_Text,
                                        Cid = cid,
                                    });
                            }
                        }

                        break;
                    }
                }
                #endregion

            }
            _iqcCheckReportRep.Context.Ado.BeginTran();
            if (iqcCheckList.Count > 0)
            {
                await _iqcCheckReportRep.AsInsertable(iqcCheckList.ToArray())
                    .AddSubList(x => x.FG_InvDetail).ExecuteCommandAsync();
            }
            if (fqcList.Count > 0)
            {
                await _fqcReportRep.AsInsertable(fqcList.ToArray())
                .AddSubList(x => x.FG_InvDetail).ExecuteCommandAsync();
            }

            _iqcCheckReportRep.Context.Ado.CommitTran();
            return iqcCheckList;
        }
        catch (Exception ex)
        {
            throw Oops.Bah(ex.Message);
        }
    }
    #endregion
}

